/* http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/  */
/*Test*/

var drawing = false;
var canvas = document.getElementById('canvas');
var svgns = "http://www.w3.org/2000/svg";
var polyLineId;
var activePolyline;

//var context = canvas.getContext('2d');

//Function to resize the canvas
(function() {
	polyLineId = 0;
    mySvg = document.getElementById('mySvg');

    // resize the svg to fill browser window dynamically
    window.addEventListener('resize', resizeSvg, false);

    function resizeSvg() {
        mySvg.width = window.innerWidth;
        mySvg.height = window.innerHeight;
    }
    resizeSvg();
})();

/**
 *@function
 *function to display the position x and y of the mouse
 *in bottom of the screen 
*/
function writeMessage(position) {	
	var coordinates = document.getElementById('coordinates');
	var userName = document.getElementById('userName');
	
	coordinates.innerHTML = "(X:"+position.x+") (Y:"+position.y+")"; 
	userName.innerHTML = (canvasViewModel.userName);
}

/**
 * @function
 * Get Position of the mouse in the canvas
*/
function getMousePosition(element, evt) {
    var rect = element.getBoundingClientRect();
    return {
    	x: evt.clientX - rect.left,
    	y: evt.clientY - rect.top
    };
}

/**
 * @event
 * MouseMove SVG
 */
canvas.addEventListener('mousemove', function(evt) {
	var mousePosition = getMousePosition(canvas, evt);
    writeMessage(mousePosition);
    if(drawing){
    	drawLineSVG(mySvg, mousePosition);
    }
}, false);

/**
 * @event
 * MouseDown SVG
 */
//set the drawing on and off
canvas.addEventListener('mousedown', function(evt) {
	drawing = !drawing;
	if(drawing){
		activePolyline = addNewPolyline();
	}
	var mousePosition = getMousePosition(canvas, evt);
	previousPoint = mousePosition;	
}, false);

function addNewPolyline(){
	polyLineId++;
	mySvg = document.getElementById('mySvg');
	var shape = document.createElementNS("http://www.w3.org/2000/svg", 'polyline');;

	shape.setAttribute("id", "pl"+polyLineId);
	shape.style.stroke = "#900"; 
	shape.style.strokeWidth = "2px";
	mySvg.appendChild(shape);
	
	return "pl"+polyLineId;
}

function drawLineSVG(mySvg, position){    
    var pl = document.getElementById(activePolyline);
    var point = mySvg.createSVGPoint();
    point.x = position.x;
    point.y = position.y;
    pl.points.appendItem(point);
}
